package cn.linjianhui.api.client.invoker.impl;

import cn.linjianhui.api.client.invoker.ClientAuthenticator;
import cn.linjianhui.api.client.invoker.HttpRequestParam;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.HttpResponse;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Getter
@Setter
public class HttpClientTokenAuthenticator implements ClientAuthenticator {

    private String user;
    private String token;
    private String appKey;
    private String appToken;
    private String client;
    private HttpRequestParam requestParam;

    public HttpClientTokenAuthenticator(String user, String token, String appKey, String appToken, String client) {
        this.user = StringUtils.isEmpty(user) ? "" : user;
        this.token = StringUtils.isEmpty(token) ? "" : token;
        this.appKey = StringUtils.isEmpty(appKey) ? "" : appKey;
        this.appToken = StringUtils.isEmpty(appToken) ? "" : appToken;
        this.client = StringUtils.isEmpty(client) ? "" : client;
    }

    @Override
    public void authenticate() {
        if(requestParam != null) {
            requestParam.getHeaders().put("Token", this.token);
            requestParam.getHeaders().put("User", this.user);
            requestParam.getHeaders().put("AppKey", this.appKey);
            requestParam.getHeaders().put("AppToken", this.appToken);
            requestParam.getHeaders().put("Client", this.client);
        }
    }

    public void refreshToken(HttpResponse response) {
        Object responseToken = response.getHeaders("Token");
        if(!ObjectUtils.isEmpty(responseToken)) {
            this.token = responseToken.toString();
        }

        Object responseAppToken = response.getHeaders("AppToken");
        if(!ObjectUtils.isEmpty(responseAppToken)) {
            this.appToken = responseAppToken.toString();
        }
    }

}
